//ID == Njc5NDQ3Mzg3OTE1MTU3NTE0.Xp5OGA.kSWnKogGtU5VCjdcHZKKfC9b7wQ
//bottest general channel = 679396695842488344
//bottest stam react = 679406359539744794

//game design general = 704820244564279430
//game design bot = 704822995939622963

const Discord = require('discord.js')
const client = new Discord.Client()
const testGeneral = client.channels.get("679396695842488344")
//const fs = require("fs")

function readProjList() {
    fs.readFile("num", 'utf-8',  function(err, data) {
        if (err) console.log(err);
        //console.log(data);
        projectList = data.toString()
        //for (i = 0; i < projectList.length; i++) { console.log(projectList[i]) }
    });
}

function writeProjList(data) {
    fs.writeFile("num", data, (err) => {
        if (err) console.log(err);
        console.log("Successfully Written to File.");
    });
}

let numAdd = 0

client.on('ready', () => {
    console.log("Connected as " + client.user.tag)
    readProjList()

    client.user.setActivity("you guys be awesome", {type:"WATCHING"})

    client.guilds.forEach((guild) => {
        console.log(guild.name)
        guild.channels.forEach((channel) =>{
            console.log(` - ${channel.name} | ${channel.type} | ${channel.id}`)
        })
        guild.roles.forEach((role) => {
            console.log(` - ${role.name} | ${role.id}`)
        })
    })

    let generalChannel = client.channels.get("679396695842488344")
    generalChannel.send("I'm online")
})

client.on('message', (receivedMessage) => {

    nowhereLog = client.channels.get("679363245181501442")

    if (receivedMessage.author == client.user) {
        return
    }
    if (receivedMessage.content == "Good bot" || receivedMessage.content == "good bot"){
        receivedMessage.channel.send("Thanks")
    }
    if (receivedMessage.content.startsWith("~")) {
        processCommand(receivedMessage)
    }
})

function processCommand(receivedMessage) {
    let fullCommand = receivedMessage.content.substr(`1`);
    let splitCommand = fullCommand.split(" ")

    let primaryCommand = splitCommand[0];

    let arguments = splitCommand.slice(1);

    if (primaryCommand == "help") {
        helpMenu(arguments, receivedMessage)
    } else if (primaryCommand == "ping") {
           pong(receivedMessage);
    } else if (primaryCommand == "collatz") {
        conjecture(receivedMessage, arguments);
    } else if (primaryCommand == "laws") {
        lawCode(receivedMessage)
    } else if (primaryCommand == "multiplicative") {
        multiplicative(receivedMessage, arguments);
    } else if (primaryCommand == "projects") {
        projects(receivedMessage, arguments, projectList)
    } else if (primaryCommand == "add") {
        console.log(numAdd)
        addNumbers(receivedMessage, arguments, numAdd)
    } else if (primaryCommand == "mvp") {
        showMVP(receivedMessage)
    } else if (primaryCommand == "tutorial") {
        showTuts(receivedMessage, arguments)
    } else { 
        receivedMessage.channel.send("Invalid command. `~help` for a list of commands.")
    }
}

function multiplicative(receivedMessage, arguments){
    if (arguments.length >= 2){
        receivedMessage.channel.send("One number only please!")
    } else if (arguments < 10) {
        receivedMessage.channel.send("Please choose a number above 10.")
    }

    console.log("Multiplicitive initiated")

    let numMain = arguments[0]
    let i = 1
    let digitCount = 0
    let mathsNum = 0
    let currentNum = 11
    let numList = []
    let numListLength

    while (currentNum >= 10) {
        let numSize = numMain.toString().length
        let j = 0;
        let numMultiplies = []

        if (i > 1000) {
            console.log("Failure!")
            receivedMessage.channel.send("Failed to compute :( sorry")
            return
        }

        console.log(i + ' | -----------------')
        for (digitCount = 0; digitCount < numSize; digitCount++) {
            //pluck out leftmost number of the number
            let placeTake = Math.pow(10, (numMain.toString().length))
            mathsNum = numMain / placeTake
            if (mathsNum < 1) {
                mathsNum *= 10;
                mathsNum = Math.floor(mathsNum)
            }

            console.log('mathsNum | numMain')
            console.log(" - | " + mathsNum + " | " /*+ temp*/ + " | " + numMain + ' |')

            //put the number into new array
            numMultiplies[j] = mathsNum;
            j++;

            console.log('numMultiplies array')
            console.log("- || " + numMultiplies + " ||")

            //remove leftmost number
            numMain = numMain - (mathsNum * Math.pow(10, numMain.toString().length-1))
        }
        //currentNum = numMultiplies.forEach

        //set the currentnum to 1, multiply the new nummultiplies into it
        currentNum = 1
        j = numMultiplies.length
        for (let k = 0; k < j; k++) {
            currentNum *= numMultiplies[k]
            console.log('currentNum = ' + currentNum + ' | k = ' + k)
        }

        numMain = currentNum
        numList[i - 1] = numMain
        console.log('currentNum | i | mathsNum | numMain')
        console.log(currentNum + " | " + i + " | " + mathsNum + " | " + numMain)

        receivedMessage.channel.send(currentNum)
        i++
    }

    numListLength = numList.length
    for (m = 0; m < numListLength; m++) {
        console.log('>> ' + numList[m])
    }
    receivedMessage.channel.send(arguments[0] + " reached a single digit in " + i + " turns.")
    
}

// Ported to Python
function conjecture(receivedMessage, arguments) {
    if (arguments.length >= 2) {
        receivedMessage.channel.send("Too many numbers! Please only use one number.")
        return
    } else if (arguments < 1) {
        receivedMessage.channel.send("Please include a number greater than 0.")
        return
    }

    console.log("Collatz initiated.")

    let collatzNum = arguments[0];
    let original = collatzNum;
    let i = 0

    while (collatzNum != 1) {
        if (collatzNum < 1) {
            receivedMessage.channel.send("Sorry, something went wrong in the program!")
            return
        }
        if (collatzNum % 2 == 0) {
            collatzNum = collatzNum / 2
            i++
        } else {
            collatzNum = collatzNum * 3 + 1
            i++
        }
    }

    receivedMessage.channel.send(original + " reached 1 in " + i + " turns.")
}

// Ported to Python
function pong(receivedMessage) {
    receivedMessage.channel.send("🏓 Pong!")
    console.log('pinged')
}

let projectList = []
let projString = ""

function projects(receivedMessage, arguments, projectList){
    if (arguments.length == 0) {
        receivedMessage.channel.send("Current to-do: ``` - Establish a name```")
        /*readProjList()
        for (x = 0; x < projectList.length; x++) { console.log(projectList[x]) }
        receivedMessage.channel.send(projectList)*/

    } if (arguments.length == 1) {
        if (arguments[0] == "completed") {
            receivedMessage.channel.send("No projects completed!")
        }
    }
    if (arguments.length > 1) {
        if (arguments[0] == "add") {
            /*var data = "New File Contents" + "\n"
            projectList.push(data)
            readProjList()
            //projString = projectList.toString()
            console.log(projectList)
            writeProjList(projectList)
            readProjList()
            receivedMessage.channel.send("Added to list!")*/
            client.fetchUser('275062639426666496')
                .then(user => {user.send(arguments.toString())})
        }
    }
}

function addNumbers(receivedMessage, arguments, numAdd) {
    
    /*fs.readFileSync("number", 'utf-8', function(err, data) {
        console.log(data); 
        numAdd = data
        console.log(numAdd)
        
    });*/

    numAdd = fs.readFileSync("number")
    console.log("numAdd = " + numAdd)

    if (arguments.length == 0) {
        numAdd++
        console.log(numAdd)
        receivedMessage.channel.send("Added number by 1\nNew number: " + numAdd)
    } else if (arguments.length > 1) {
        receivedMessage.channel.send("Too many arguments!")
        return
    } else if (arguments.length == 1 && arguments[0] > 0 && arguments[0] < 100000000) {
        toAdd = arguments[0].toString()
        console.log(toAdd)
        for (let n = 0; n != toAdd; n++) {
            console.log(n)
            numAdd++
        }
        console.log(numAdd + " | " + toAdd)
        receivedMessage.channel.send("Added number by " + toAdd + "\nNew number: " + numAdd)
    } else if (arguments.length == 1 && arguments[0] <= 0 && arguments[0] > 100000000) {
        receivedMessage.channel.send("Please choose a number above 0!")
        return
    } else if (arguments.length == 1 && arguments[0] >= arguments[0] < 100000000) {
        receivedMessage.channel.send("Number too big! Please choose a smaller number.")
    }

    fs.writeFile("number", numAdd, (err) => {
        if (err) console.log(err);
        console.log("Successfully Written to File.");
    });
}

function showMVP(receivedMessage) {
    receivedMessage.channel.send("The current minimum viable product requirements are: ``` - Main player movement\n - Secondary player movement\n - Basic attack\n - Switching bw 2 ppl\n - Basic enemy```")
}

// Ported to Python
function showTuts(receivedMessage, arguments) {
    if (arguments.length < 1) { // If no specific requests given, give list
        receivedMessage.channel.send("Current available tutorials are:```gdscript (GDScript introduction)\ngame (Making your first game)\nc++ (Using C++ with Godot)\nblender (23 episode playlist all about using Blender)```Use `~tutorial [tutorial]` to view one.")
        return
    } else if (arguments.length > 1) { // If more than one requested, show none
        receivedMessage.channel.send("Please only choose one tutorial!")
        return
    }

    // if's for the various tutorials to be displayed
    if (arguments[0].toString() == "gdscript") {
        receivedMessage.channel.send("**Introduction to GDscript - Godot tutorial** by GDQuest\nhttps://youtu.be/K5-5j4H4Ypo")
    } else if (arguments[0].toString() == "game") {
        receivedMessage.channel.send("**Extra Credits: Making your First Game** by Extra Credits\nhttps://www.youtube.com/playlist?list=PLhyKYa0YJ_5C6QC36h5eApOyXtx98ehGi")
    } else if (arguments[0].toString() == "c++") { 
        receivedMessage.channel.send("**Using C++ with Godot (GDNative Tutorial) \"Ten Thousand Subs\"** by Thoughtquake\n https://www.youtube.com/watch?v=XPcSfXsoArQ")
    } else if (arguments[0].toString() == "blender") {
        receivedMessage.channel.send("**Blender Beginner Tutorial Series** by Blender Guru\nhttps://www.youtube.com/playlist?list=PLjEaoINr3zgEq0u2MzVgAaHEBt--xLB6U")
    } else {
        receivedMessage.channel.send("Sorry! That tutorial doesn't exist. To see available tutorials, use `~tutorial`.")
    }
}

// Already in Python
function helpMenu(arguments, receivedMessage){
    let channel = receivedMessage.channel
    let askHelp = arguments.includes("help")
    let pingAsk = arguments.includes("ping")
    let askCollatz = arguments.includes("collatz")
    let askMultiply = arguments.includes("multiplicative")
    let projects = arguments.includes("projects")
    let adding = arguments.includes ("add")
    let askMVP = arguments.includes("mvp")
    let askTut = arguments.includes("tutorial")

    if (arguments.length == 0){
        receivedMessage.channel.send("**Commands:**```~help\n~ping\n~collatz\n~multiplicative\n~projects\n~add\n~mvp\n~tutorial```Use `~help [command]` for more information.")
    } else if (arguments.length >= 2) {
        receivedMessage.channel.send("Too many arguments! Please choose one command you need help with.")
    } else if (askHelp == true) {
        receivedMessage.channel.send("Shows the help menu. `~help [command]` to use, or just `~help` for all commands.")
    } else if (pingAsk == true) {
        receivedMessage.channel.send("Pings the robot. Just `~ping`.")
    } else if (askCollatz == true) {
        receivedMessage.channel.send("Runs a number through the Collatz game (if n is even, n/2; if n is odd, 3n+1).\nUse `~collatz [number]` to play around with it.")
    }  else if (askMultiply == true) {
        receivedMessage.channel.send("Runs a number through the multiplicative principle (ie, each digit multiplied to each other). `~multiplicative [number]` to play with it.")
    } else if (projects == true) {
        receivedMessage.channel.send("Displays a list of current projects. Use `~projects completed` to see a list of completed projects. `~project add [project]` to add new projects to the to-do.")
    } else if (adding == true){
        receivedMessage.channel.send("Adds a number to a running counter. `~add` to add 1, and `~add [x]` to add a different number.")
    } else if (askMVP) {
        receivedMessage.channel.send("Shows a list of the current Minimum Viable Product requirements.")
    } else if (askTut) {
        channel.send("Shows a list of available tutorials. Use `~tutorial [tutorial]` to view one in the list.")
    } else { receivedMessage.channel.send("Unrecognised command. Please try again.") }
}

/*client.on('guildMemberAdd', member => {
    console.log('User ' + member.user.username + ' has joined the server')
    let bottestNewUser = client.channels.get("679560083729940502")
    let vghsGeneral = client.channels.get("701952908001804298")

    bottestNewUser.send(member.user.username + " has entered the server")
    vghsGeneral.send(member.user.username + " has entered the server. Welcome to VGHS!")

    //let autoRole = member.guild.roles.find("Nowhere", "678037590917513218")

    member.addRole("678037590917513218")
})*/

client.login("Njc5NDQ3Mzg3OTE1MTU3NTE0.Xkxe2w.7M3lsSQpsSrGkF3WRsYeIGWLYBk");


/*          /\ 
           /  \
 _________/____\_________
 '-.     /      \     ,-'
    '-, /        \ ,-'
       /-.      ,-\
      /   '-,.-'   \
     /    ,-''-.    \
    /  ,-'      '-.  \
   /,-'            '-.\ */
